#!/usr/bin/env python3
"""
DCR Explorer (Link Edition) - Tony's Director64
A dashboard-style explorer where DCR files are presented as links.
Single-click to launch.
"""

import os
import sys
import tkinter as tk
from tkinter import ttk, messagebox
import subprocess
import platform
from datetime import datetime

# ─────────────────────────────────────────────────────────────
#  PREMIUM DARK THEME
# ─────────────────────────────────────────────────────────────
BG_DARK      = "#0d1117"
BG_PANEL     = "#161b22"
BG_HOVER     = "#1c2128"
ACCENT_BLUE  = "#58a6ff"
ACCENT_GLOW  = "#1f6feb"
TEXT_PRIMARY = "#c9d1d9"
TEXT_DIM     = "#8b949e"
TEXT_LINK    = "#58a6ff"
BORDER       = "#30363d"
HEADER_BG    = "#010409"

def human_size(n_bytes):
    for unit in ("B", "KB", "MB", "GB"):
        if n_bytes < 1024: return f"{n_bytes:.1f} {unit}"
        n_bytes /= 1024
    return f"{n_bytes:.1f} TB"

class DCRLinkExplorer(tk.Tk):
    def __init__(self, scan_dir):
        super().__init__()
        self.title("DCR Explorer • Tony's Director64")
        self.geometry("850x600")
        self.configure(bg=BG_DARK)
        self.scan_dir = scan_dir
        
        self._build_ui()
        self.refresh()

    def _build_ui(self):
        # Header
        header = tk.Frame(self, bg=HEADER_BG, height=60)
        header.pack(fill="x", side="top")
        header.pack_propagate(False)
        
        tk.Label(header, text="◈  DCR Explorer", bg=HEADER_BG, fg=ACCENT_BLUE,
                 font=("Helvetica Neue", 18, "bold")).pack(side="left", padx=20)
        
        # Refresh Button
        self.refresh_btn = tk.Label(header, text="↻ Refresh", bg=BG_PANEL, fg=TEXT_PRIMARY,
                               font=("Helvetica Neue", 10, "bold"), padx=12, pady=5, cursor="hand2")
        self.refresh_btn.pack(side="right", padx=20)
        
        def on_refresh_hover(e): self.refresh_btn.config(bg=BG_HOVER, fg=ACCENT_BLUE)
        def on_refresh_leave(e): self.refresh_btn.config(bg=BG_PANEL, fg=TEXT_PRIMARY)
        self.refresh_btn.bind("<Enter>", on_refresh_hover)
        self.refresh_btn.bind("<Leave>", on_refresh_leave)
        self.refresh_btn.bind("<Button-1>", lambda e: self.refresh())

        tk.Label(header, text="Single-click a file to launch instantly", 
                 bg=HEADER_BG, fg=TEXT_DIM, font=("Helvetica Neue", 10, "italic")).pack(side="right")

        # Main Content Scrollable Area
        self.canvas = tk.Canvas(self, bg=BG_DARK, highlightthickness=0)
        self.scroll_y = ttk.Scrollbar(self, orient="vertical", command=self.canvas.yview)
        self.scroll_frame = tk.Frame(self.canvas, bg=BG_DARK)

        self.scroll_frame.bind("<Configure>", lambda e: self.canvas.configure(scrollregion=self.canvas.bbox("all")))
        self.canvas.create_window((0, 0), window=self.scroll_frame, anchor="nw", width=830)
        self.canvas.configure(yscrollcommand=self.scroll_y.set)

        self.canvas.pack(side="left", fill="both", expand=True, padx=10, pady=10)
        self.scroll_y.pack(side="right", fill="y")

        # Status Bar
        self.status = tk.Frame(self, bg=HEADER_BG, height=30)
        self.status.pack(fill="x", side="bottom")
        self.status_label = tk.Label(self.status, text=f"Scanning: {self.scan_dir}", bg=HEADER_BG, fg=TEXT_DIM, font=("Helvetica Neue", 9))
        self.status_label.pack(side="left", padx=10)

    def refresh(self):
        # Clear existing items
        for widget in self.scroll_frame.winfo_children():
            widget.destroy()

        try:
            files = [f for f in os.listdir(self.scan_dir) if f.lower().endswith(".dcr")]
            files.sort()
            
            # Micro-animation for feedback
            if hasattr(self, 'refresh_btn'):
                orig_fg = self.refresh_btn.cget("fg")
                self.refresh_btn.config(fg="#34C759") # Success Green
                self.after(500, lambda: self.refresh_btn.config(fg=orig_fg))
                
        except Exception as e:
            messagebox.showerror("Error", f"Could not access directory:\n{e}")
            return

        if not files:
            tk.Label(self.scroll_frame, text="No .dcr files found in this directory.", 
                     bg=BG_DARK, fg=TEXT_DIM, font=("Helvetica Neue", 11), pady=40).pack()
            return

        for fname in files:
            self._add_file_link(fname)

    def _add_file_link(self, fname):
        fpath = os.path.join(self.scan_dir, fname)
        stats = os.stat(fpath)
        size_str = human_size(stats.st_size)
        mod_time = datetime.fromtimestamp(stats.st_mtime).strftime("%Y-%m-%d")

        # Container Frame (Link Row)
        row = tk.Frame(self.scroll_frame, bg=BG_PANEL, cursor="hand2", pady=8, padx=15)
        row.pack(fill="x", pady=2)
        
        # Hover Effects
        def on_enter(e, r=row): r.config(bg=BG_HOVER)
        def on_leave(e, r=row): r.config(bg=BG_PANEL)
        row.bind("<Enter>", on_enter)
        row.bind("<Leave>", on_leave)
        
        # Icon
        tk.Label(row, text="🎬", bg=row["bg"], fg=ACCENT_BLUE, font=("Segoe UI Symbol", 14)).pack(side="left", padx=(0, 10))
        
        # File Name (The "Link")
        lbl_name = tk.Label(row, text=fname, bg=row["bg"], fg=TEXT_LINK, 
                          font=("Helvetica Neue", 12, "bold"), anchor="w")
        lbl_name.pack(side="left", fill="x", expand=True)

        # Metadata
        tk.Label(row, text=f"{size_str}  |  {mod_time}", bg=row["bg"], fg=TEXT_DIM, 
                 font=("Helvetica Neue", 9)).pack(side="right", padx=10)

        # Click Event (Single Click)
        def launch(e=None, path=fpath):
            self._trigger_launch(path)

        for widget in [row, lbl_name]:
            widget.bind("<Button-1>", launch)
            # Propagate hover events to children
            widget.bind("<Enter>", lambda e, r=row: r.config(bg=BG_HOVER))
            widget.bind("<Leave>", lambda e, r=row: r.config(bg=BG_PANEL))

    def _trigger_launch(self, path):
        # We don't launch directly here on Mac to avoid permission issues.
        # Instead, we write the path to a temp file that our shell parent is watching,
        # or we just trigger the shell command.
        # For simplicity in this revised version, we will call a specific shell command back.
        
        # We use the internal launcher mechanism by creating a "signal" file
        signal_file = "/tmp/director_launch_signal"
        with open(signal_file, "w") as f:
            f.write(path)
        
        # Keep open as requested
        self.status_label.config(text=f"Launch Triggered: {os.path.basename(path)}", fg="#34C759")
        self.after(3000, lambda: self.status_label.config(text=f"Scanning: {self.scan_dir}", fg=TEXT_DIM))

if __name__ == "__main__":
    scan_path = sys.argv[1] if len(sys.argv) > 1 else os.getcwd()
    app = DCRLinkExplorer(scan_path)
    app.mainloop()
